package com.gpStudy.distributed.netty;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NIOServerDemo1 {

    private int port = 8080;

    private Selector selector;

    private ByteBuffer buffer = ByteBuffer.allocate(1024);

    public NIOServerDemo1(int port) {
        this.port = port;

        try {

            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

            serverSocketChannel.bind(new InetSocketAddress(this.port));

            serverSocketChannel.configureBlocking(false);

            selector = Selector.open();

            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void listen(){


        try {

            while (true){
                selector.select();

                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = keys.iterator();

                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    
                    process(key);
                }


            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void process(SelectionKey key) throws IOException {

        if (key.isAcceptable()) {

            ServerSocketChannel server = (ServerSocketChannel) key.channel();
            SocketChannel channel = server.accept();
            channel.configureBlocking(false);

            key = channel.register(selector, SelectionKey.OP_READ);

        }else if (key.isReadable()) {

            SocketChannel channel = (SocketChannel) key.channel();
            int read = channel.read(buffer);
            if (read > 0) {
                buffer.flip();
                String content = new String(buffer.array(), 0, read);

                System.out.println("接收的内容为：" + content);

                key = channel.register(selector, SelectionKey.OP_WRITE);

                key.attach(content);

            }


        }else if (key.isWritable()) {

            SocketChannel channel = (SocketChannel) key.channel();

            String content = (String) key.attachment();

            channel.write(ByteBuffer.wrap(("输出："+content).getBytes()));

            channel.close();

        }


    }
    
    public static void main(String[] args){
        new NIOServerDemo1(8080).listen();
    }
    
}
